##
## 提供指定Git代码仓库列表和代码分支， 按提交者进行归类，对代码提交行数进行统计。
## a shell script to investigate the submission status of git repository
##
## author: peipeihh
## date:   2022-10-26
##
## Steps,
## 1. download the script and place under a folder
## 2. create a file repoList.txt which list all the git repositories to be parsed
## 3. run the script, sh ./analyzeGitRepo.sh "2020-01-01" "2021-07-20"
## 4. an output example like as following,
##
##    name  new-code-lines  delete-code-lines   all
##    peipeihh 1500 223 1723
##   
##    Note: from left to right represent the committer name, the number of new code lines, the number of deleted code lines, the total number of code lines(both the new and deleted)
##

# 1. parse the date of start/end

sinceDate=$1
untilDate=$2

if [ ! $sinceDate ]; then
    sinceDate="1970-01-01"
fi

if [ ! $untilDate ]; then
    untilDate=`date '+%Y-%m-%d'`
fi

echo "the period of analysis: sinceDate = $sinceDate, untilDate = $untilDate"

# 2. prepare the repository folder

repoTmp=$PWD
repoList="$PWD/repoList.txt"
repoLocalDir="$PWD/repoLocal"
repoReportFile="$PWD/tmpReport.txt"
repoFinalReportFile="$PWD/finalReport.txt"

if [ -d "$repoLocalDir" ]; then
    rm -rf $repoLocalDir;
fi
mkdir -p $repoLocalDir;

if [ -f "$repoReportFile" ]; then
    rm $repoReportFile;
fi
touch $repoReportFile;

if [ ! -f "$repoList" ]; then
    echo "Cannot find repoList.txt, please create it and list all the git repositories to be analyzed, a format is as following, "
    echo "```"
    echo "git@gitee.com:pphh/simple-demo.git master"
    echo "```"
    exit 1
fi

# 3. clone the git repo into local and do the investigation

i=1
cat $repoList | while read line
do
    cd $repoLocalDir

    repoDef=( $line )
    repoName=${repoDef[0]}
    repoBranch=${repoDef[1]}

    if [ -z $repoName ]; then
        continue
    fi

    if [ -z $repoBranch ]; then
        repoBranch="master"
    fi

    repoFolder="./$i-repo-$repoBranch"
    let i++
    echo
    echo "start to clone the repository: $repoName, branch = $repoBranch, folder = $repoFolder"
    git clone $repoName -b $repoBranch $repoFolder
    echo "clone is completed!"

    cd $repoFolder
    echo "try to investigate the submission status of the repository: $repoName, branch = $repoBranch"
    git log --format='%aN' | sort -u | while read name; do git log --numstat --author="$name" --since="$sinceDate" --until="$untilDate" | awk 'BEGIN {add=0;subs=0;all=0} {if($1~/^[0-9]+/){add += $1; subs += $2; all += $1 + $2 }} END {printf "'$name'\t%s\t%s\t%s\n", add, subs, all }' >> $repoReportFile; done;
         
done

# 4. merge the results

cat $repoReportFile | awk '{ newLines[$1]+=$2;deleteLines[$1]+=$3;all[$1]+=$4 } END {for (i in all) print i,newLines[i],deleteLines[i],all[i];}' > $repoFinalReportFile
rm $repoReportFile
echo
echo "name\tnew-code-lines\tdelete-code-lines\tall"
cat $repoFinalReportFile